package com.qingchi.web.config.filter;

import com.socialuni.web.config.redis.RedisUtil;
import com.socialuni.web.utils.IpUtil;
import com.socialuni.web.utils.UserUtils;
import com.qingchi.web.model.DO.user.SocialUserDO;
import com.socialuni.social.constant.ErrorCode;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserAuthInterceptor implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object arg2, Exception arg3) {
    }

    /*
     * 处理请求完成后视图渲染之前的处理操作
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) {
    }

    @Resource
    private RedisUtil redisUtil;

    /*
     * 进入controller层之前拦截请求
     * 在请求处理之前进行调用（Controller方法调用之前
     */
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object o) {

        SocialUserDO user = UserUtils.getMineUser();

        String ip = IpUtil.getIpAddr(req);

        String ipKey = "ipKey:" + ip;

        Object keyCountObj = redisUtil.get(ipKey);
        //如果已经有了赋值
        if (keyCountObj != null) {
            int count = (Integer) keyCountObj;
            //限制1分钟访问50次
            if (count > 3000) {
                //这里只提示未登录
                res.setStatus(ErrorCode.IP_LIMIT_ERROR);
                return false;
            }
            long expireTime = redisUtil.getExpire(ipKey);
            //否则访问次数加1
            count = count + 1;
            redisUtil.set(ipKey, count, expireTime);
        } else {
            redisUtil.set(ipKey, 1, 60);
        }

        String uri = req.getRequestURI();
        System.out.println(uri);
        System.out.println(req.getMethod());
        if ((req.getMethod().equals(RequestMethod.OPTIONS.name())
                || req.getMethod().equals(RequestMethod.GET.name())
                || uri.equals("/")
                || uri.contains("test")
                //初始化的请求
                || uri.contains("report/queryReportTypes")
                //查询首页轮播图
                || uri.contains("oauth")
                || uri.contains("qingchi/queryHomeSwipers")
                || uri.contains("tag/queryTags")
                || uri.contains("tag/queryHotTags")
                || uri.contains("tag/queryTagTypes")
                || uri.contains("tag/queryHotTagType")
                || uri.contains("/queryDistricts")
                || uri.contains("/queryHotDistricts")
                || uri.contains("/devUser/queryDevUserDetail")
                || uri.contains("/app/sendErrorLog")
                //渠道登录的方法
                || uri.contains("user/providerLogin")
                || uri.contains("queryProvinceDistricts")
                || uri.contains("queryHotProvinceDistricts")
                || uri.contains("queryOtherHomeTypeTalks")
                || uri.contains("readChat")
                || uri.contains("queryChats")
                || uri.contains("refreshKeywords")
                || uri.contains("refreshConfigMap")
                || uri.contains("refreshRedis")
                || uri.contains("qqPayNotify")
                || uri.contains("wxPayNotify")
                || uri.contains("login")
                || uri.contains("user/platformLogin")
                || uri.contains("user/miniAppLogin")
                || uri.contains("user/appLogin")
                || uri.contains("app/checkUpdate")
                || uri.contains("match/queryMatchUsers")
                || uri.contains("appLogin")
                || uri.contains("wxLogin")
                || uri.contains("authentication")
                || uri.contains("sendAuthCode")
                || uri.contains("match/queryUsers")
                || uri.contains("talk/queryTalks")
                || uri.contains("message/queryMessages")
                || uri.contains("/webSocketServer")
                || uri.contains("/myHandler")
                || uri.contains("/queryUserTalks")
                || uri.contains("/queryTalkDetail")
                || uri.contains("/queryUserDetail")
                || uri.contains("/queryAppInitData")
                || uri.contains("/queryAppInitDataLoad")
                || uri.contains("/queryAppInitDataLoad1")
                || uri.contains("/queryAppInitDataReady")
                || uri.contains("/img")
                || uri.contains("/css")
                //这里只查询没被封禁的
                || user != null)
                //不允许读取idcard信息
                && !uri.contains("/img/idCard")
        ) {
            return true;
        } else {
            String origin = req.getHeader("Origin");
            res.setHeader("Access-Control-Allow-Origin", origin);
            res.setHeader("Access-Control-Allow-Methods", "*");
            res.setHeader("Access-Control-Allow-Headers", "Origin,Content-Type,Accept,token,X-Requested-With");
            res.setHeader("Access-Control-Allow-Credentials", "true");
            //这里只提示未登录
            res.setStatus(ErrorCode.NOT_LOGGED_ERROR);
            return false;
        }
    }
}